/*
 * Copyright 2002-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.context.support;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.core.OrderComparator;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.lang.Nullable;

/**
 * Delegate for AbstractApplicationContext's post-processor handling.
 *
 * @author Juergen Hoeller
 * @author Sam Brannen
 * @since 4.0
 */
final class PostProcessorRegistrationDelegate {

	private PostProcessorRegistrationDelegate() {
	}


	/**
	 *
	 * 整体结构大致为：
	 * 子类型：先调用postProcessBeanDefinitionRegistry--->再调用postProcessBeanFactory
	 * 父类型：调用postProcessBeanFactory
	 *
	 * 作用：把所有的BeanFactoryPostProcessor 及 BeanDefinitionRegistryPostProcessor的类型，进行注册，并进行调用
	 *
	 * ！！！注意特例！！！
	 * add方法添加的 没有注册到 BeanDefinitionMap , 但是他会执行
	 * 问题：为什么add方法添加 BeanFactoryPostProcessor 为什么不需要注册
	 * 核心原因：add操作时这个对象已经new创建，不需要spring创建，当然也就不需要spring进行注册
	 *
	 *
	 * 下面是所有的BeanFactoryPostProcessor 及 BeanDefinitionRegistryPostProcessor类型的来源：
	 * --->spring内置的
	 * 1. 内置
	 *           BeanDefinitionResitryPostProcessor(子)
	 *                    ConfigurationClassPostProcessor(同时也实现了PriorityOrdered )
	 *           BeanFactoryPostProcessor(父)
	 *                      EventListenerMethodProcessor(未实现PriorityOrdered和Ordered接口)
	 *
	 * --->程序员开发
	 * 实现哪一个接口就是哪一个类型的Postprocessor
	 * 2. Add方法添加
	 * 3. @Component添加
	 *
	 */
	public static void invokeBeanFactoryPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

		// Invoke BeanDefinitionRegistryPostProcessors first, if any.
		//记录已经处理的BeanDefinitionRegistryPostProcessors，防止后续再处理
		Set<String> processedBeans = new HashSet<>();


		//	下面这块if代码，是BeanDefinitionRegistry(子)类型的，首先进行注册
		//	先调用BeanDefinitionRegistry(子)中的方法--->postProcessBeanDefinitionRegistry
		//	再调用BeanFactoryPostProcessor(父)中的方法--->postProcessBeanFactory
		if (beanFactory instanceof BeanDefinitionRegistry) {
			BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
			//父
			List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
			//子
			List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

			/**
			 * 下面只针对add添加的
			 * 对 List<BeanFactoryPostProcessor> 这个集合里面的 postprocessor 进行区分父子关系，
			 * 因为 List 泛型定义的是父类接口，所以有可能在list集合中也可能会有子类的情况
			 * 默认情况下不会走这段代码，因为 beanFactoryPostProcessors --->List<BeanFactoryPostProcessor>该集合默认是空的
			 * 除非用户在初始化的时候主动注入了 BeanFactoryPostProcessor或者其子类, 后续在 refresh 的时候,该List集合才会有东西
			 *
			 * addBeanFactoryPostProcessor其实就是向 List<BeanFactoryPostProcessor>这个集合里面添加元素，所以后面的list才会有东西
			 * 			AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
			 * 			ctx.register(AppConfig.class);
			 * 			ctx.addBeanFactoryPostProcessor(new MyBeanDefinitionRegistryPostProcessor());
			 * 			ctx.refresh();
			 * */
			for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
				//子类型:BeanDefinitionRegistryPostProcessor
				if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
					BeanDefinitionRegistryPostProcessor registryProcessor =
							(BeanDefinitionRegistryPostProcessor) postProcessor;
					//这里这个PostProcessor一定是通过add添加进来的
					//所以这里会调用通过add添加进来的postprocessor的postProcessorBeanDefinitionRegistry方法
					//！！！注意:但是这里并没有将通过add添加进来的进行注册--->beanDefinitionMap
					registryProcessor.postProcessBeanDefinitionRegistry(registry);//add子-->子
					registryProcessors.add(registryProcessor);
				}
				//父类形:BeanFactoryPostProcessor
				else {
					regularPostProcessors.add(postProcessor);
				}
			}

			// Do not initialize FactoryBeans here: We need to leave all regular beans
			// uninitialized to let the bean factory post-processors apply to them!
			// Separate between BeanDefinitionRegistryPostProcessors that implement
			// PriorityOrdered, Ordered, and the rest.
			//该list集合目前是空的，后续将会存储Spring内置的BeanDefintionRegistryPostProcessor(ConfigurationClassPostProcessor )
			List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();


			/**
			 * First、Next、Finally这三块代码作用基本一致，只是针对实现的接口不一样
			 * First:  需要实现 PriorityOrdered 接口
			 * Next:   需要实现 Ordered 接口
			 * Finally:	不实现上述两个接口
			 */
			// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
			String[] postProcessorNames =
					beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
				if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
					//注意，下面这三种情况，都会调用getbean方法，也就是说此时会进行创建对象并放到单例池中
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					processedBeans.add(ppName);
				}
			}
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			registryProcessors.addAll(currentRegistryProcessors);
			//因为在这一块只有Spring内置的ConfigurationClassPostProcessor既实现了BeanDefinitionRegistryPostProcessor接口又实现了PriorityOrdered接口
			//所以下面的代码调用的其实是ConfigurationClassPostProcessor的调用--->postProcessorBeanDefinitionRegistry
			//通过下面的这行代码，spring注册了加有注解类的BD(@Compoent、@Bean、@Import等)
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);//spring子--->子
			currentRegistryProcessors.clear();

			// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
			//下面这个一般不进行，因为Spring内置的BeanDefinitionRegistryPostProcessors没有实现Ordered接口的，除非程序员自己加入
			postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
				if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					processedBeans.add(ppName);
				}
			}
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			registryProcessors.addAll(currentRegistryProcessors);
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
			currentRegistryProcessors.clear();

			// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
			//最后这种情况是针对：程序员不是通过add添加BeanDefinitionRegistryPostProcessors，
			//而是通过在BeanDefinitionRegistryPostProcessor的实现类上加入@Component或者@Configuration注解
			boolean reiterate = true;
			while (reiterate) {
				reiterate = false;
				//从beanDefinitionMap中拿BeanDefinitionRegistryPostProcessor类型的bean(注意此时add方法添加的不在map里面)
				//所以此时拿到的结果只可能是
				// 1、spring内置的ConfigurationClassPostProcessor
				// 2、通过@Component修饰 自定义 BeanDefinitionRegistryPostProceesor(因为此时已经将所有的顶级注解都注册到Map中了，所有他可以获取到)
				postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
				for (String ppName : postProcessorNames) {
					//判断是否已经处理过，显然spring内置的ConfigurationClassPostProcessor已经被处理过了，只有第二种情况是没有被处理的
					if (!processedBeans.contains(ppName)) {
						currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
						processedBeans.add(ppName);
						reiterate = true;
					}
				}
				sortPostProcessors(currentRegistryProcessors, beanFactory);
				registryProcessors.addAll(currentRegistryProcessors);
				//在这会进行调用 通过@Component修饰 自定义 BeanDefinitionRegistryPostProceesor的方法 ---->postProcessorBeanDefinitionRegistry
				invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);//@Component子--->子
				currentRegistryProcessors.clear();
			}

			// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
			/**
			 * 之前调用的是BeanDefinitionRegistryPostProcessor：子接口定义的方法 postProcessBeanDefinitionRegistry
			 *
			 * 下面这两个调用的是BeanFactoryPostProcessor：父接口定义的方法 postProcessBeanFactory
			 */
			//子:BeanDefinitionRegistryPostProcessor
			// 1.手工编码 add添加子类型 （目前没有）---->
			// 如果add添加的是子类型，不会进行注册，只将他记录在这个子的list集合里面，(这一步都是之前代码做的，并且已经调用了子类型的方法)
			// 所以下面的代码针对add添加的来说，现在调用的就是父类型的方法
			//*****************************************************************************************************
			// 2.通过@Component或者@Configuration修饰的自定义 BeanDefinitionRegistryPostProceesor，调用其实现父接口的方法
			//*****************************************************************************************************
			// 3.spring内置类型  其实主要就是 ConfigurationClassPostProcessor
			//			相当于上面会调用ConfigurationClassPostProcessor实现的子接口的方法，下面这行会调用ConfigurationClassPostProcessor实现父接口的方法
			invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);//spring子、add子、@Component子 --->父

			/**其实下面这个代码主要就是针对如果add添加的是父类型，让他执行**/
			//父:BeanFactoryPostProcessor
			//1. 手工编码 add添加父类型 （目前没有）----->
			// 如果add添加的是父类型，不会进行注册，只将他记录在这个父的list集合里面，(这一步都是之前代码做的，因为没有子类型的方法，所以之前的代码只会记录在list集合不会调用子类型方法)
			// 所以下面的代码针对add添加的来说，调用的就是父类型的方法
			// *****************************************************************************************************
			//2. spring内置没有这个类型，所以只看是否有add添加
			invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);//add父--->父
		}

		else {
			// Invoke factory processors registered with the context instance.
			invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
		}



		// Do not initialize FactoryBeans here: We need to leave all regular beans
		// uninitialized to let the bean factory post-processors apply to them!
		/**
		 * 下面最后这块代码处理的是BeanFactoryPostProcessor，会进行调用 postProcessBeanFactory
		 *	如果在程序员 没有自己定义BeanFactoryPostProcessor实现类的情况下
		 *  那么他就调用 默认的 EventListenerMethodProcessor
		 *  如果你自已定义了 在这里也会调用你程序员自己定义的类型
		 */

		//根据一个类型 去 BeanDefinitionMap中获取对应bean的id值获取 BeanFactoryPostProcessor类型的所有 bean的id值
		//注意这里也会获取到BeanDefinitionRegistryPostProcessors类型的，因为获取的是父接口类型，子接口类型一定也是属于父接口类型的
		String[] postProcessorNames =
				beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

		// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
		// Ordered, and the rest.
		List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
		List<String> orderedPostProcessorNames = new ArrayList<>();
		List<String> nonOrderedPostProcessorNames = new ArrayList<>();
		for (String ppName : postProcessorNames) {
			//这里进行判断的主要目的就是将子接口类型BeanDefinitionRegistryPostProcessors排除掉，只处理真正为BeanFactoryPostProcessor父接口类型的
			if (processedBeans.contains(ppName)) {
				// skip - already processed in first phase above
			}
			else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
			}
			else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
				orderedPostProcessorNames.add(ppName);
			}
			else {
				nonOrderedPostProcessorNames.add(ppName);
			}
		}

		//下面的逻辑跟上面相似，判断是否实现这两个接口
		// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

		// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
		List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
		for (String postProcessorName : orderedPostProcessorNames) {
			orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}
		sortPostProcessors(orderedPostProcessors, beanFactory);
		invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

		// Finally, invoke all other BeanFactoryPostProcessors.
		//EventListenerMethodProcessor没有实现上述两个接口，所以会走下面的代码
		List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
		for (String postProcessorName : nonOrderedPostProcessorNames) {
			//！注意：这里也调用了getBean，所以也会进行创建对象并放到单例池里面
			nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}
		//调用postProcessBeanFactory方法
		invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);//spring父、@Component父---->父

		// Clear cached merged bean definitions since the post-processors might have
		// modified the original metadata, e.g. replacing placeholders in values...
		beanFactory.clearMetadataCache();
	}


	/**
	 * 下面的代码整体是进行beanpostprocessor的注册(BD-->对象--->存储在DefaultListableBeanFactory.beanPostProceesors属性中)
	 *
	 * 下面是beanpostprocessor的来源:
	 * 1.Spring内置
	 *      @Value @Autowired
	 *         AutowiredAnnotationBeanPostProcessor
	 *
	 *      @Resource  @PostConstruct  @PreDestroy
	 *         CommonAnnotationBeanPostProcessor
	 *
	 * 2.程序员开发
	 *        程序员通过@Component修饰的BeanPostProcessor
	 *        会在invokeBeanFactoryPostProcessors方法中完成注册
	 *
	 * 3.通过add添加(与beanfactorypostprocessor类似，通过new创建对象直接add添加，并不会在beandefinitionMap和singletonObjects中出现)
	 * 		  ApplicationContextAwareProcessor
	 *        ConfigurationClassPostProcessor#ImportAware
	 *        ApplicationListenterDetector
	 *
	 * 注意：
	 * 在这段代码运行之前
	 * 我们spring提供的 2个内置的BeanPostProcessor--->AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor
	 * 以及自己通过@Component注解 创建BeanPostProcessor仅仅是由BD存在，还没有进行实例化
	 */
	public static void registerBeanPostProcessors(
			ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

		//此时从beanDefinitionMap中拿BeanPostProcessor的类型只会拿到Spring内置的两个和我们自己通过@Component注解添加的，不会拿到通过add添加的，原因见上
		String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

		// Register BeanPostProcessorChecker that logs an info message when
		// a bean is created during BeanPostProcessor instantiation, i.e. when
		// a bean is not eligible for getting processed by all BeanPostProcessors.
		/**
		 * 下面是 beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length 这三个参数详细解释
		 * beanFactory.getBeanPostProcessorCount()：代表直接从Beanpostprocessor属性中拿，这时候Spring内置的以及我们自己通过@Component注册的还没有注册到Beanpostprocessor属性中，
		 * 											所以此时get到的就是spring自己通过add添加的三个：ApplicationContextAwareProcessor
		 * 																					 ConfigurationClassPostProcessor#ImportAware
		 * 	        				 														 ApplicationListenterDetector
		 * “1”:代表他自己(BeanPostProcessorChecker),下面就会进行add操作
		 * postProcessorNames.length：是之前从BDmap中拿到的，代表spring内置和程序员添加的
		 */
		int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
		//主要做安全性检查，看是否有beanpostprocessor少注册的问题
		beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));


		//下面代码与之前beanfactorypostprocessor大同小异，按照实现接口不同分类然后按顺序注册执行
		// Separate between BeanPostProcessors that implement PriorityOrdered,
		// Ordered, and the rest.
		List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
		List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
		List<String> orderedPostProcessorNames = new ArrayList<>();
		List<String> nonOrderedPostProcessorNames = new ArrayList<>();
		for (String ppName : postProcessorNames) {
			if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				//在这会通过getBean创建对象放进单例池里面，后续可以进行注册
				BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
				priorityOrderedPostProcessors.add(pp);
				if (pp instanceof MergedBeanDefinitionPostProcessor) {
					internalPostProcessors.add(pp);
				}
			}
			else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
				orderedPostProcessorNames.add(ppName);
			}
			else {
				nonOrderedPostProcessorNames.add(ppName);
			}
		}

		//Spring内置的两个AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor既实现了priorityOrdered接口也实现了MergedBeanDefinition接口，
		// 所以在priorityOrderedPostProcessors和internalPostProcessors两个集合中都有他们俩
		// First, register the BeanPostProcessors that implement PriorityOrdered.
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

		// Next, register the BeanPostProcessors that implement Ordered.
		List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
		for (String ppName : orderedPostProcessorNames) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			orderedPostProcessors.add(pp);
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		sortPostProcessors(orderedPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, orderedPostProcessors);

		//这里会进行注册我们自己通过@Component注解添加到beanpostprocessor
		// Now, register all regular BeanPostProcessors.
		List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
		for (String ppName : nonOrderedPostProcessorNames) {
			//同样会调用getBean方法先创建对象
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			nonOrderedPostProcessors.add(pp);
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

		// Finally, re-register all internal BeanPostProcessors.
		sortPostProcessors(internalPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, internalPostProcessors);

		// Re-register post-processor for detecting inner beans as ApplicationListeners,
		// moving it to the end of the processor chain (for picking up proxies etc).
		//注意：这里beanpostprocessor属性中已经有ApplicationListenerDetector，这里的add目的是删除之前的，并将这个移动到list的末尾
		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
	}

	private static void sortPostProcessors(List<?> postProcessors, ConfigurableListableBeanFactory beanFactory) {
		// Nothing to sort?
		if (postProcessors.size() <= 1) {
			return;
		}
		Comparator<Object> comparatorToUse = null;
		if (beanFactory instanceof DefaultListableBeanFactory) {
			comparatorToUse = ((DefaultListableBeanFactory) beanFactory).getDependencyComparator();
		}
		if (comparatorToUse == null) {
			comparatorToUse = OrderComparator.INSTANCE;
		}
		postProcessors.sort(comparatorToUse);
	}

	/**
	 * Invoke the given BeanDefinitionRegistryPostProcessor beans.
	 */
	private static void invokeBeanDefinitionRegistryPostProcessors(
			Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry) {

		for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
			postProcessor.postProcessBeanDefinitionRegistry(registry);
		}
	}

	/**
	 * Invoke the given BeanFactoryPostProcessor beans.
	 */
	private static void invokeBeanFactoryPostProcessors(
			Collection<? extends BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) {

		for (BeanFactoryPostProcessor postProcessor : postProcessors) {
			postProcessor.postProcessBeanFactory(beanFactory);
		}
	}

	/**
	 * Register the given BeanPostProcessor beans.
	 */
	private static void registerBeanPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {

		if (beanFactory instanceof AbstractBeanFactory) {
			// Bulk addition is more efficient against our CopyOnWriteArrayList there
			((AbstractBeanFactory) beanFactory).addBeanPostProcessors(postProcessors);
		}
		else {
			for (BeanPostProcessor postProcessor : postProcessors) {
				beanFactory.addBeanPostProcessor(postProcessor);
			}
		}
	}


	/**
	 * BeanPostProcessor that logs an info message when a bean is created during
	 * BeanPostProcessor instantiation, i.e. when a bean is not eligible for
	 * getting processed by all BeanPostProcessors.
	 */
	private static final class BeanPostProcessorChecker implements BeanPostProcessor {

		private static final Log logger = LogFactory.getLog(BeanPostProcessorChecker.class);

		private final ConfigurableListableBeanFactory beanFactory;

		private final int beanPostProcessorTargetCount;

		public BeanPostProcessorChecker(ConfigurableListableBeanFactory beanFactory, int beanPostProcessorTargetCount) {
			this.beanFactory = beanFactory;
			this.beanPostProcessorTargetCount = beanPostProcessorTargetCount;
		}

		@Override
		public Object postProcessBeforeInitialization(Object bean, String beanName) {
			return bean;
		}

		@Override
		public Object postProcessAfterInitialization(Object bean, String beanName) {
			if (!(bean instanceof BeanPostProcessor) && !isInfrastructureBean(beanName) &&
					this.beanFactory.getBeanPostProcessorCount() < this.beanPostProcessorTargetCount) {
				if (logger.isInfoEnabled()) {
					logger.info("Bean '" + beanName + "' of type [" + bean.getClass().getName() +
							"] is not eligible for getting processed by all BeanPostProcessors " +
							"(for example: not eligible for auto-proxying)");
				}
			}
			return bean;
		}

		private boolean isInfrastructureBean(@Nullable String beanName) {
			if (beanName != null && this.beanFactory.containsBeanDefinition(beanName)) {
				BeanDefinition bd = this.beanFactory.getBeanDefinition(beanName);
				return (bd.getRole() == RootBeanDefinition.ROLE_INFRASTRUCTURE);
			}
			return false;
		}
	}

}
